package com.coder.utils;

import com.coder.zexception.ServerErrorException;

public class DecodeUtil {
	
	public static int getInt(byte[] bytes) {
		return (0xff & bytes[0]) | (0xff00 & (bytes[1] << 8))
				| (0xff0000 & (bytes[2] << 16))
				| (0xff000000 & (bytes[3] << 24));
	}

	public static byte[] hexStringToByteArray(String s) {
		int len = s.length();
		byte[] data = new byte[len / 2];
		for (int i = 0; i < len; i += 2) {
			data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
					.digit(s.charAt(i + 1), 16));
		}
		return data;
	}
	
	public static float fromBytes2float(byte[] bytes){
		int intVal = getInt(bytes);
		return Float.intBitsToFloat(intVal);
	}
	
	public static float convertHex2float(String hex){
		
		if(hex.length()!=8){
			new ServerErrorException("hex must has 8 characters").printStackTrace();
		}
		
		byte[] bytes = hexStringToByteArray(hex);
		
		int intVal = getInt(bytes);
		
		return Float.intBitsToFloat(intVal);
	}

	/**将浮点数组转化为字符串，使用符号“|”分割，“|”在java正则表达式中为特殊字符*/
	public static String floats2Str(float[] vals){
		String res = "";
		for(int i=0;i<vals.length;i++){
			res += vals[i]+"|";
		}
		return res;
	}
	
	/**将一个字符串转化为浮点数组，字符串用“|”分割，需要转义*/
	public static float[] str2floats(String str){
		String[] strs = str.split("\\|");
		float[] res = new float[strs.length];
		for(int i=0;i<strs.length;i++){
			res[i] = Float.parseFloat(strs[i]);
		}
		return res;
	}
	
}
